package com.bing.utils.utilstool;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Mr.HRL
 * @Description: redis工具类
 * @Date: 2019-10-02 18:46
 * @Version: 1.0
 */

@Component
public class RedisUtils {
    @Autowired
    private  RedisTemplate<String, String> redisTemplate;

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public  String get(final String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 写入缓存
     */
    public  boolean set(final String key, String value,long timeout) {
        boolean result = false;
        if (StringUtils.isEmpty(key)) return result;
        try {
            redisTemplate.opsForValue().set(key, value,timeout, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 更新缓存
     */
    public  boolean getAndSet(final String key, String value) {
        boolean result = false;
        if (StringUtils.isEmpty(key)) return result;
        try {
            redisTemplate.opsForValue().getAndSet(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 删除缓存
     */
    public  boolean delete(final String key) {
        boolean result = false;
        if (StringUtils.isEmpty(key)) return result;
        try {
            redisTemplate.delete(key);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 判断缓存是否存在
     */
    public  boolean haskey(final String key){
        boolean result = false;
        if (StringUtils.isEmpty(key)) return result;
        try {
            result  = redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}


